package eclant.ant.tasks;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;

import eclant.eclipse.jdt.ClasspathWalker;

public class EchoClasspath extends Task
{
	private IProject project = null;
	private boolean failOnError = true;
	private boolean exportedOnly = false;

	@Override
	public void execute() throws BuildException
	{
		IJavaProject javaProject = JavaCore.create(getEclipseProject());
		ClasspathEntriesLogger result = new ClasspathEntriesLogger(this, failOnError);
		try
		{
			ClasspathWalker.walkClasspath(javaProject, exportedOnly, result);
			result.printTree();
		}
		catch (JavaModelException e)
		{
			throw new BuildException(e, getLocation());
		}
	}

	public void setProject(String projectName)
	{
		IWorkspace workspace = ResourcesPlugin.getWorkspace();
		project = workspace.getRoot().getProject(projectName);
	}

	public void setExportedonly(boolean exportedOnly)
	{
		this.exportedOnly = exportedOnly;
	}

	public void setFailonerror(boolean fail)
	{
		this.failOnError = fail;
	}

	protected IProject getEclipseProject()
	{
		if (this.project != null)
		{
			return this.project;
		}
		else
		{
			String buildFilePath = getProject().getProperty("ant.file");

			IWorkspace workspace = ResourcesPlugin.getWorkspace();
			IPath path = Path.fromOSString(buildFilePath);
			IFile buildFile = workspace.getRoot().getFileForLocation(path);
			return buildFile.getProject();
		}
	}
}
